﻿using System;
using System.Net;
using System.Net.Sockets;
using UnityEngine;

namespace Nirvana
{
    public sealed class NetClientConnect
    {
        public NetClient.ConnectDelegate connectDelegate;
        public NetClient netclient;
        public int port;
        public bool isconnect;

        public void Connect(IAsyncResult asyncResult)
        {
            //要解析的主机名或IP地址。
            IPAddress[] array = Dns.EndGetHostAddresses(asyncResult);
            if (array.Length == 0)
            {
                Debug.LogError("Connect failed: can not resolve DNS.");
                this.connectDelegate(false);
                return;
            }

            try
            {
                IPAddress ipaddress = array[0];
                if(ipaddress.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    this.netclient.socket = new Socket(ipaddress.AddressFamily, SocketType.Stream, ProtocolType.IPv6);
                    this.netclient.socket.BeginConnect(ipaddress, this.port, new AsyncCallback(ConnectedSuccess), this);

                }
                else
                {
                    this.netclient.socket = new Socket(ipaddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                    this.netclient.socket.BeginConnect(ipaddress, this.port, new AsyncCallback(ConnectedSuccess), this);
                }
            }
            catch (Exception ex)
            {
                Debug.LogError("Connect failed: " + ex.Message);
                this.connectDelegate(false);
            }

        }

        private void ConnectedSuccess(IAsyncResult asyncResult)
        {

            var u = (NetClientConnect)asyncResult.AsyncState;
            try
            {
                this.netclient.socket.EndConnect(asyncResult);
                if (u != null)
                {
                    u.isconnect = asyncResult.IsCompleted;
                    Scheduler.PostTask(()=> { u.connectDelegate(asyncResult.IsCompleted); });
                }
            }
            catch (Exception ex)
            {
                Debug.LogError("Socket ConnectedSuccess: " + ex.Message);
                if (u.connectDelegate != null)
                {
                    Scheduler.PostTask(() => { u.connectDelegate(false); });
                }
            }
        }



    }
}